package cc.linker.steplink.crm.merchant.controller.acs;


import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.acs.RechargeService;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/recharge")
public class RechargeController {

    @Autowired
    private RechargeService rechargeService;

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * @Description: 充值亏损订单
     * @Param: [params, payMode]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/7/16 9:34
     * @Version: 1.12.6
     **/
    @PostMapping("/rechargeByLoss")
    public String saveInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        Integer payMode = userinfo.getPayMode();
        Boolean ifSales = userinfo.getSaler();
        String customerId = orgId;
        if (ifSales) {
            // 联盟商家（小b）
            customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            params.put("customerId", customerId);
        }
        params.put("orgId",orgId);
        String rechargeSn = TransactionOrderUtil.TYPE_RECHARGE + purchaseProcessService.getUniquePrimaryKey();
        params.put("rechargeSn",rechargeSn);
        //插入充值记录
        rechargeService.add(params);
        return rechargeSn;
//        Map resultMap = this.rechargeByLoss(params,payMode);
//        String tradeSn = "";
//        String clintType = "";
//        if(!StringUtils.isEmpty(resultMap.get("txsn"))){
//            tradeSn = resultMap.get("txsn").toString();
//            clintType = resultMap.get("txsn").toString();
//            params.put("tradeSn",tradeSn);
//            params.put("clintType",clintType);
//            //修改tradeSn，clintType
//            rechargeService.updateTradeSn(params);
//        }
    }

    /**
     * @Description: 封装充值参数
     * @Param: [params, payMode]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/7/16 9:37
     * @Version:
     **/
    private Map rechargeByLoss(Map<String, Object> params,Integer payMode) {
        //参数定定义下面的方法上面会有
        String orgId = params.get("orgId").toString();
        String amount = "0";
        if(!StringUtils.isEmpty(params.get("amount"))){
            amount = params.get("amount").toString();
            if("0".equals(amount)){
                throw GlobalException.build("充值金额不能为0");
            }
        }
        String alias = "";
        if(payMode == 3){
            alias = stringRedisTemplate.opsForValue().get("alias:orgId_linker");
            if(StringUtils.isEmpty(alias)) {
                alias = maiBaoLaService.getAliasByLinker();
                stringRedisTemplate.opsForValue().set("alias:orgId_linker",alias);
            }
        }
        if(payMode == 2){
            alias = stringRedisTemplate.opsForValue().get("alias:orgId_"+orgId);
            if(StringUtils.isEmpty(alias)) {
                alias = maiBaoLaService.getAlias(orgId);
                stringRedisTemplate.opsForValue().set("alias:orgId_"+orgId,alias);
            }
        }
        String clintType = alias;
        String frontUrl = "";
        if(!StringUtils.isEmpty(params.get("frontUrl"))){
            frontUrl = params.get("frontUrl").toString();
        }
        String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
        String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
        String notifyUrl = systemProperties.getScrmUrl() + "/recharge/ordernotify";
        String payType = "";
        if(!StringUtils.isEmpty(params.get("payWay"))){
            String payWay = params.get("payWay").toString();
            if("1".equals(payWay)){
                payType = "ALIPAY_SCAN";
            }else if("2".equals(payWay)){
                payType = "WX_SCAN";
            }
        }
        String source = "1";
        String validateType = "0";
        String orderSn = "";
        if(!StringUtils.isEmpty(params.get("rechargeSn"))){
            orderSn = params.get("rechargeSn").toString();
        }
        String customerId = "";
        if(!StringUtils.isEmpty(params.get("customerId"))){
            customerId = params.get("customerId").toString();
        }
        String goodsName = "亏损充值";
        String fee = "0";
        Map resMap = this.recharge(amount,fee,clintType,customerId,frontUrl,industryCode,industryName,notifyUrl,payType,source,null,null,validateType,goodsName,orderSn);
        resMap.put("clintType",clintType);
        return  resMap;
    }

    /**
     * @Description: 充值自测接口
     * @Param: [amount, fee, clintType, customerId, frontUrl, industryCode, industryName, notifyUrl, payType, source, appId, openID, validateType, goodsName, orderSn]
     * @Param: amount 充值金额包含手续费
     * @Param: fee 	手续费
     * @Param: clintType 	应用别名
     * @Param: customerId 	用户ID
     * @Param: frontUrl 	充值完成前端跳转地址
     * @Param: industryCode 	行业代码
     * @Param: industryName 	行业名称
     * @Param: notifyUrl 	支付回调地址
     * @Param: payType 	支付方式(WX-公众号支付；XCX-微信小程序支付，ALIPAY_SCAN-支付宝正扫；WX_SCAN-微信正扫)
     * @Param: source 	访问终端类型:1手机；2PC
     * @Param: appId 	应用的APPID
     * @Param: openID 	充值用户微信OPENID
     * @Param: validateType 	交易验证方式：0-无验证；1-短信验证码；2-支付密码
     * @Param: goodsName 	商品定义
     * @Param: orderSn 		平台交易流水号
     * @Return: java.lang.String
     * @Author: ch
     * @Date: 2020/7/15 14:47
     * @Version:  1.12.6
     **/
    @GetMapping("/recharge")
    public Map recharge(String amount,String fee,String clintType,String customerId,String frontUrl,String industryCode,String industryName,String notifyUrl,
                           String payType,String source,String appId,String openID,String validateType,String goodsName,String orderSn){
        Map<String, Object> map = new HashMap<>();
        map.put("amount", amount);
        map.put("clintType", clintType);
        map.put("customerId", customerId);
        map.put("industryCode", industryCode);
        map.put("industryName", industryName);
        map.put("notifyUrl",notifyUrl);
        map.put("payType", payType);
        map.put("source", source);
        map.put("orderSn", orderSn);
        if(!StringUtils.isEmpty(fee)){
            map.put("fee", fee);
        }else {
            map.put("fee", "0");
        }
        if(!StringUtils.isEmpty(goodsName)){
            map.put("goodsName", goodsName);
        }
        if(!StringUtils.isEmpty(appId)){
            map.put("appId", appId);
        }
        if(!StringUtils.isEmpty(frontUrl)){
            map.put("frontUrl", frontUrl);
        }
        if(!StringUtils.isEmpty(openID)){
            map.put("openID", openID);
        }
        if(!StringUtils.isEmpty(openID)){
            map.put("validateType", validateType);
        }
        // 请求支付网关
        Map resultMap;
        String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_RECHARGE_ONLINE;
        try {
            LOGGER.info("通联支付请求参数==={}", JSON.toJSONString(map));
            String result = httpService.doPost(url, JSON.toJSONString(map), WcPayConstant.JSON);
            resultMap = rechargeService.callResultProcess(result);
        } catch (Exception e) {
            LOGGER.error("支付网关调用异常", e);
            throw GlobalException.build("支付网关调用异常");
        }
        return  resultMap;
    }


    /**
     * @Description: 充值回调
     * @Param: [params]
     * @Return: void
     * @Author: ch
     * @Date: 2020/7/16 9:18
     * @Version:  1.12.6
     **/
    @PostMapping("/ordernotify")
    public void orderNotify(@RequestBody Map<String, Object> params) throws Exception {
        params.put("tradeSn", params.get("transactionId"));
        params.put("orderSn", params.get("outTradeNo"));
        //修改充值记录状态
        rechargeService.updateStatus(params);
    }

    /**
     * @Description: 批量转账自用接口
     * @Param: [params]
     * @Return: void
     * @Author: ch
     * @Date: 2020/7/16 9:34
     * @Version:  1.12.6
     **/
    @PostMapping("/transferBatch")
    public void transferBatch(@RequestBody Map<String, Object> params) throws Exception {
        rechargeService.transferBatchToTL(params);
    }

}
